package cn.tedu.store.product.webapi.service.impl;

import cn.tedu.store.commons.pojo.portal.vo.ProductDetailVO;
import cn.tedu.store.commons.pojo.product.dto.SpuAddNewDTO;
import cn.tedu.store.commons.pojo.product.dto.SpuUpdateDTO;
import cn.tedu.store.commons.pojo.product.entity.HomeNewProduct;
import cn.tedu.store.commons.pojo.product.entity.HomeRecommendProduct;
import cn.tedu.store.commons.pojo.product.entity.Spu;
import cn.tedu.store.commons.pojo.product.entity.SpuDetail;
import cn.tedu.store.commons.pojo.product.vo.*;
import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.web.JsonPage;
import cn.tedu.store.product.webapi.mapper.*;
import cn.tedu.store.product.service.ISpuService;
import cn.tedu.store.product.webapi.util.IdUtils;
import cn.tedu.store.commons.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@DubboService
public class SpuServiceImpl implements ISpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private HomeRecommendProductMapper homeRecommendProductMapper;
    @Autowired
    private HomeNewProductMapper homeNewProductMapper;

    @Override
    public void addNew(SpuAddNewDTO spuAddNewDTO) {
        log.debug("开始处理[添加商品]请求 参数:{}", spuAddNewDTO);
        //判断品牌是否有效

        BrandStandardVO brandStandardVO = brandMapper.getStandardById(spuAddNewDTO.getBrandId());
        if (brandStandardVO == null) {
            String message = "添加商品失败,要绑定的品牌不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (brandStandardVO.getEnable() == 0) {
            String message = "添加商品失败,要绑定的品牌已被禁用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //判断分类是否有效

        CategoryStandardVO categoryStandardVO = categoryMapper.getStandardById(spuAddNewDTO.getCategoryId());
        if (categoryStandardVO == null) {
            String message = "添加商品失败,要绑定的分类不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (categoryStandardVO.getEnable() == 0) {
            String message = "添加商品失败,要绑定的分类已被禁用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        if (categoryStandardVO.getIsParent() == 1) {
            String message = "新增商品失败，尝试绑定的类别包含子级类别，不允许使用此类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        AlbumStandardVO album = albumMapper.getStandardById(spuAddNewDTO.getAlbumId());
        if (album == null) {
            String message = "新增商品失败，尝试绑定的相册不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //准备执行添加
        Spu spu = new Spu();
        Long id = IdUtils.getId();//生成唯一id
        BeanUtils.copyProperties(spuAddNewDTO, spu);
        //补全spu信息
        spu.setId(id);
        spu.setIsDeleted(0);//未删除
        spu.setBrandName(brandStandardVO.getName());
        spu.setCategoryName(categoryStandardVO.getName());
        spu.setSales(0);//销量
        spu.setCommentCount(0);//评论数量
        spu.setPositiveCommentCount(0);//好评数量
        spu.setIsChecked(0);//审核状态
        int rows = spuMapper.insert(spu);
        if (rows != 1) {
            String message = "操作失败,服务器忙,请稍后再试![错误代码：1]";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        //判断是否为新品
        if(spu.getIsNewArrival() == 1){
            HomeNewProduct homeNewProduct = new HomeNewProduct();
            homeNewProduct.setProductId(id);
            homeNewProduct.setProductName(spu.getName());
            homeNewProduct.setRecommendStatus(0);//默认不推荐
            homeNewProduct.setSort(100);
            homeNewProductMapper.insert(homeNewProduct);
        }
        //判断是否是推荐商品
        if(spu.getIsRecommend() == 1){
            HomeRecommendProduct homeRecommendProduct = new HomeRecommendProduct();
            homeRecommendProduct.setProductId(id);
            homeRecommendProduct.setProductName(spu.getName());
            homeRecommendProduct.setRecommendStatus(1);
            homeRecommendProduct.setSort(100);
            homeRecommendProductMapper.insert(homeRecommendProduct);
        }
        // 创建SpuDetail对象
        SpuDetail spuDetail = new SpuDetail();
        spuDetail.setSpuId(id);
        spuDetail.setDetail(spuAddNewDTO.getDetail());
        rows = spuDetailMapper.insert(spuDetail);
        if (rows != 1) {
            String message = "操作失败！服务器忙，请稍后再次尝试！[错误代码：2]";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理[删除SPU]业务 参数:{}", id);
        // 检查尝试删除的SPU是否存在
        SpuStandardVO queryResult = spuMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "删除SPU失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        setDeleted(id);
        if(queryResult.getIsNewArrival() == 1){
            homeNewProductMapper.deleteByProductId(id);
        }
        if(queryResult.getIsRecommend() == 1){
            homeRecommendProductMapper.deleteByProductId(id);
        }
    }

    @Override
    public int count() {
        log.debug("统计商品数量...");
        return spuMapper.count();
    }

    @Override
    public void setDeleted(Long id) {
        updateStatusById(id,1,"delete");
    }

    @Override
    public void setNotDeleted(Long id) {
        updateStatusById(id,0,"delete");
    }

    @Override
    public void setPublished(Long id) {
        updateStatusById(id,1,"publish");
    }

    @Override
    public void setNotPublished(Long id) {
        updateStatusById(id,0,"publish");
    }

    @Override
    public void setNewArrival(Long id) {
        updateStatusById(id,1,"newArrival");
    }

    @Override
    public void setNotNewArrival(Long id) {
        updateStatusById(id,0,"newArrival");
    }

    @Override
    public void setRecommend(Long id) {
        updateStatusById(id,1,"recommend");
    }

    @Override
    public void setNotRecommend(Long id) {
        updateStatusById(id,0,"recommend");
    }

    @Override
    public void setChecked(Long id) {
        updateStatusById(id,1,"check");
    }

    @Override
    public void setUnChecked(Long id) {
        updateStatusById(id,1,"check");
    }

    @Override
    public void update(Long id, SpuUpdateDTO spuUpdateDTO) {
        log.debug("开始处理[修改商品详情]业务 参数:{},{}", id, spuUpdateDTO);
        SpuStandardVO spuStandardVO = spuMapper.getStandardById(id);
        if (spuStandardVO == null) {
            String message = "修改商品详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuUpdateDTO,spu);
        spu.setId(id);
        int rows = spuMapper.updateById(spu);
        if (rows != 1) {
            String message = "操作失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

    }

    @Override
    public SpuStandardVO getStandardById(Long id) {
        log.debug("开始处理[获取商品详情]业务 参数:{}", id);
        SpuStandardVO spuStandardVO = spuMapper.getStandardById(id);
        if (spuStandardVO == null) {
            String message = "获取商品详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return spuStandardVO;
    }

    @Override
    public ProductDetailVO getPortalDetailById(Long id) {
        log.debug("开始处理[获取展示详情]业务 参数:{}", id);
        return spuMapper.getPortalDetailById(id);
    }

    @Override
    public JsonPage<SpuListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取后台管理商品列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(spuMapper.list());
    }

    @Override
    public JsonPage<SpuListItemVO> portalList(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取前台商品列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(spuMapper.portalList());
    }

    @Override
    public JsonPage<SpuListItemVO> recommendList(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取前台推荐商品列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(spuMapper.recommendList());
    }

    @Override
    public JsonPage<SpuListItemVO> newProductList(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取前台新品列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(spuMapper.newProductList());
    }

    @Override
    public JsonPage<SpuListItemVO> listByBrand(Long brandId, Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取指定品牌商品列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(spuMapper.listByBrand(brandId));
    }

    @Override
    public JsonPage<SpuListItemVO> listByCategory(Long categoryId, Integer pageNum, Integer pageSize) {
        log.debug("开始处理[获取指定分类商品列表]业务");
        PageHelper.startPage(pageNum, pageSize);
        return JsonPage.restPage(spuMapper.listByCategory(categoryId));
    }

    private void updateStatusById(Long id, Integer value,String type){
        String[] deleteTips = {"未删除","已删除"};
        String[] publishTips = {"未上架","上架"};
        String[] newTips = {"非新品","新品"};
        String[] recommendTips = {"不推荐","推荐"};
        String[] checkTips = {"未审核","已审核"};
        String[] tips;
        switch (type){
            case "delete": tips=deleteTips;break;
            case "publish": tips=publishTips;break;
            case "newArrival": tips=newTips;break;
            case "recommend": tips=recommendTips;break;
            default: tips=checkTips;
        }
        SpuStandardVO queryResult = spuMapper.getStandardById(id);
        if(queryResult == null){
            String message = "设置"+tips[value]+"分类失败,该分类不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Spu spu = new Spu();
        spu.setId(id);
        switch (type){
            case "delete": spu.setIsDeleted(value);break;
            case "publish": spu.setIsPublished(value);break;
            case "newArrival": {
                spu.setIsNewArrival(value);
                if(value == 1){
                    homeNewProductMapper.deleteByProductId(id);
                    HomeNewProduct homeNewProduct = new HomeNewProduct();
                    homeNewProduct.setProductId(id);
                    homeNewProduct.setProductName(queryResult.getName());
                    homeNewProduct.setRecommendStatus(1);
                    homeNewProductMapper.insert(homeNewProduct);
                }else{
                    homeNewProductMapper.deleteByProductId(id);
                }
            }break;
            case "recommend": {
                spu.setIsRecommend(value);
                if(value == 1){
                    homeRecommendProductMapper.deleteByProductId(id);
                    HomeRecommendProduct homeRecommendProduct = new HomeRecommendProduct();
                    homeRecommendProduct.setProductId(id);
                    homeRecommendProduct.setProductName(queryResult.getName());
                    homeRecommendProduct.setRecommendStatus(1);
                    homeRecommendProductMapper.insert(homeRecommendProduct);
                }else{
                    homeRecommendProductMapper.deleteByProductId(id);
                }
            }break;
            default: spu.setIsChecked(value);
        }
        int rows = spuMapper.updateById(spu);
        if(rows != 1){
            String message = "操作失败,服务器忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }
}
